//
//  JJComposeControllerViewController.swift
//  微博1
//
//  Created by 卷卷 on 15/8/31.
//  Copyright © 2015年 JJ. All rights reserved.
//
//发微博控制器

import UIKit


class JJComposeController: JJBaseController,UITextViewDelegate{

    
    
    //工具栏底部约束
     private var toolbarBottomCons: NSLayoutConstraint?
    
    //MARK:监听方法
    @objc private func close () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发送微博
    @objc private func sendStatus () {
        print("发送微博")
    }
    
    //选照片
    @objc private func selectPicture () {
        print("选照片")
    }
    
    //MARK: -UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        
        //当textView有文字时，隐藏自定义占位符
        placrHoderLabel.highlighted = textView.hasText()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //MARK: 视图的生命周期
    override func viewDidLoad() {
        
        //注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    
    //键盘变化监听
    @objc private func keyBoardChanged(n:NSNotification){
        
        printLog(n)
        
        //获取最终的frame - 将结构体保存在字典中，存成NSValue
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        //获取动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
      toolbarBottomCons?.constant  =  -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        //激活键盘
        textView.becomeFirstResponder()
    }
    
    //MARK:创建界面
    //专门用来创建界面的函数
    override func loadView() {
        
        view = UIView()
        
        view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        prepareNav()
        
        //设置工具栏
        prepareToolBar()
        
        //设置文本框
        preparetextView()
    }
    
    //设置文本框
    private func preparetextView () {
        
        view.addSubview(textView)
        
        //自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict : [String :AnyObject] = ["top":topLayoutGuide,"tb":toolbar,"tv":textView ]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0[tv]-0|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0[top]-0[tv]-0-[tb]-0|", options: [], metrics: nil, views: viewDict))
        
        //添加占位符,添加到textView上，就是为了能同时滚动
        textView.addSubview(placrHoderLabel)
        placrHoderLabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placrHoderLabel.bounds.size)
    }
    
    
    //设置工具栏
    private func prepareToolBar () {
        
        let toolbar = UIToolbar()
        view.addSubview(toolbar)
        
        //设置背景颜色
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        //设置自动布局
        let w = UIScreen.mainScreen().bounds.width
      let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: 44))
        //纪录底部约束
       toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        //定义数组按钮
        let itemSettings = [["imageName":"juanjuan"]];
        
        //添加按钮
        var items = [UIBarButtonItem]()
        
        
        for dict in itemSettings {
            
            let button = UIButton(imageName: "imageName")
            
            //添加监听方法
            if let actionName = dict["action"]{
                
            button.addTarget(self, action:Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            items.append(UIBarButtonItem(customView: button))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    
    //设置导航栏
    private func prepareNav () {
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target:self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target:self, action: "sendStatus")
        
        //禁止发送按钮
         navigationItem.rightBarButtonItem?.enabled = false
        
        //标题视图
        let  titleView = UIView(frame: CGRectMake(0, 0, 200, 32))
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title: JJUserAccountViewModel.shareUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleLabel.addSubview(nameLabel)
        
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView

    }
    
    //MARK：懒加载
    
//    private lazy var placrHoderLabel :UILabel(tit)
    
    private lazy var textView : UITextView = {
        
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
         //允许垂直拖拽
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
    }()
    
    private lazy var toolbar = UIToolbar()
    
    private lazy var placrHoderLabel :UILabel = {

       let placrHoderLabel = UILabel()
        
        placrHoderLabel.textColor = UIColor.lightGrayColor()
        placrHoderLabel.font = UIFont.systemFontOfSize(18)
        placrHoderLabel.text = "分享新鲜事..."
        
        return placrHoderLabel
    
    }()
        
       

}
